import HttpRequest from '@/utils/HttpRequest'
import appData from '@/utils/appData'
// let base64= require('@/utils/base64.js').Base64;
	
const common = {
	checkParam:function(options, rule){
		for(var key in rule){
			if(rule[key].check_type == 'required'){
				if(!options[rule[key].name] || options[rule[key].name] == ''){
					uni.showToast({
						title:rule[key].error_msg,
						icon:'none'
					})
					
					return false;
				}
			}

			if(rule[key].check_type == 'string' ){
				var check_rule = rule[key].check_rule.split(',');
				if(options[rule[key].name].length < check_rule[0] || options[rule[key].name].length > check_rule[1]){
					uni.showToast({
						title:rule[key].error_msg,
						icon:'none'
					})
					
					return false;	
				}
			}		
			
			if(rule[key].check_type == 'telephone' ){
				if(!(/^1[345789]\d{9}$/.test(options[rule[key].name]))){
					uni.showToast({
						title:rule[key].error_msg,
						icon:'none'
					})
					
					return false;	
				}
			}		
		}
		
		return true;
	},
	//检查登录状态，有登录状态再请求数据
	wxLogin:function(){
		var path = common.getPagePath();
		var param = common.getPageParam();

		var state = {'path':path, param:param};
		state = JSON.stringify(state);
		state = base64.encode(state);
		
		// console.log(state);
		appData.wechat.goAuth(state);
	},
	isLoginState:function(){
		var token = uni.getStorageSync('token');
	
		return token ? true:false; 
	},
	//检查登录状态，没登录就去登录
	checkLoginState:function(){
		var token = uni.getStorageSync('token');
		
		// if(!token){
		// 	common.wxLogin();
		// }
	
		return token ? true:false; 
	},
	//跳转到指定页面
	navTo:function(path, loginState=true, param={}){
		if(loginState && !uni.getStorageSync('token')){
			uni.navigateTo({
				url:'/pages/auth/auth'
			});
			
			return;
		}
		
		function isEmptyObj(obj) {
		    for (var key in obj) {
		        if ({}.hasOwnProperty.call(obj, key)) return false;
		    }
		    return true;
		}
		
		if(!isEmptyObj(param)){
			path = path + '?';
			
			for(var k in param){
				path = path + k +'='+param[k] + '&';
			}
			
			path = path.substring(0, path.length-1);
		}
		
		console.log(path);
		uni.navigateTo({
			url:path
		});	
	},
	buildQuery:function(path, param){
		path = path + '?';
		
		for(var k in param){
			path = path + k +'='+param[k] + '&';
		}
		
		path = path.substring(0, path.length-1);
		
		return path;
	},
	//返回设置层级上一页
	navBack:function(delta){
		if(!delta){
			delta = 1;
		}
		
		uni.navigateBack({
			delta:delta
		})
	},
	//返回设置层级上一页
	navWaitBack:function(delta, timeout){
		if(!delta){
			delta = 1;
		}
		
		setTimeout(function(){
			uni.navigateBack({
				delta:delta
			})
		}, timeout);
	},
	//设置缓存
	setData:function(key, value){
		uni.setStorageSync(key, value);
	},
	//获取缓存
	getData:function(key){
		var val = uni.getStorageSync(key);
		
		return val ? val : '';
	},
	logout(){
		common.rmData('openid');
		common.rmData('session_key');
		common.rmData('token');
		common.rmData('invite_code');
		
		uni.switchTab({
			url:'/pages/index/index'
		})
	},
	getSysSite(key){		
		return new Promise(resolve => {
			var sysSite = common.getData('sys_site');
			if(sysSite[key]){
				resolve(sysSite[key]);
				return;
			}
			
			appData.plat.getSysConfig({}, function(resp){
				common.setData('sys_site', resp.data);
				
				resolve(resp.data[key]);
			});
		});
	},
	formatDatetimeVal(str){
		var num;
		str>10?num=str:num="0"+str;
		
		return num;
	},
	currTime(){
		var date = new Date();
		var year=date.getFullYear();//当前年份
		var month=date.getMonth();//当前月份
		var data=date.getDate();//天
		var hours=date.getHours();//小时
		var minute=date.getMinutes();//分
		var second=date.getSeconds();//秒
		
		var time = year+"-"+common.formatDatetimeVal((month+1))+"-"+common.formatDatetimeVal(data)+" "+common.formatDatetimeVal(hours)+":"+common.formatDatetimeVal(minute)+":"+common.formatDatetimeVal(second);
		
		return time;
	},
	//获取配置数据
	getAppPong:function(key){
		var appPong = uni.getStorageSync('app_pong');
		
		return appPong[key];
	},
	//获取屏幕高度
	getDeviceHeight(){
		var deviceHeight = uni.getSystemInfoSync().windowHeight;
		//返回的是px
		
		return deviceHeight;
	},
	//获取屏幕状态栏高度
	getStatusBarHeight(callback){
		// return plus.navigator.getStatusbarHeight();
		var contentTop = common.getData('content_top');
		if(contentTop){
			callback({content_top:contentTop});
		}else{
			var _this = this;
			//顶部状态栏高度
			uni.getSystemInfo({
				success: function (res) {
					var statusBarHeight = res.statusBarHeight;
					var contentTop = statusBarHeight + uni.upx2px(88);
					common.setData('content_top', contentTop);
					callback({content_top:contentTop});
				}
			});
		}
	},
	//删除缓存
	rmData:function(key){
		uni.removeStorageSync(key);
	},
	//打开内置地图
	openMap(obj){
		uni.openLocation({
			latitude: parseFloat(obj.longitude),
			longitude: parseFloat(obj.latitude),
			scale: 14,
			name:obj.name,
			address:obj.address,
			success:function(){
			
			},
			fail:function(res){
				console.log(res);
				uni.showToast({
					title:'打开地图失败',
					icon:'none'
				})
			},
		});
	},
	alert:function(title){
		uni.showToast({
			title:title,
			icon:'none'
		})
	},
	showModal:function(title, content, success, fail){
		var options = {};
		if(title && title != ''){
			options.title = title;
		}

		if(content && content != ''){
			options.content = content;
		}
	
		options.confirmColor = '#ff4341';
		options.success = function(res){
			if(res.confirm){
				success();
			}else{
				if(fail) fail();
			}
		}
			
		uni.showModal(options);
	},
	scanQRCode(callback){
		uni.scanCode({
			onlyFromCamera: true,
			success: function (res) {
				callback(res.result, res.scanType);
			}
		});
	},
	showTip:function(title,content){
		uni.showModal({
			title:title,
			content:content,
			showCancel:false,
			confirmColor:'#ff4341',
			success:function(res){
				if(res.confirm){
					
				}
			}
		})		
	},
	wePay:function(options,success,fail){
		options.success = function(res){
			success(JSON.stringify(res));
		};
		
		options.fail = function(err){
			fail(JSON.stringify(err))
		};
		
		uni.requestPayment(options);
	},
	setNavTitle:function(title){
		uni.setNavigationBarTitle({
			title:title
		})
	},
	hideKb:function(){
		uni.hideKeyboard();
	},
	showKb:function(){
		uni.showKeyboard();
	},
	copy:function(value){
		uni.setClipboardData({
			data: value
		});
	},
	getPagePath(){
		var pages = getCurrentPages();
		var route = pages[pages.length - 1].route;
		
		return route;
	},
	getPageParam(){
		var pages = getCurrentPages();
		var options = pages[pages.length - 1].options;
		
		return options;
	},
	download:function(file){
		common.alert('正在下载中...');
		uni.downloadFile({
			url: file,
			success: (res) => {
				if (res.statusCode === 200) {
					console.log(file+' 下载成功');
					common.alert('下载成功');
				}
			}
		});
	},
	downloadImage:function(file){
		common.alert('下载图片中...');
		uni.downloadFile({
			url: file,
			success: (res) => {
				// console.log(res);
				if (res.statusCode === 200) {
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: function () {
							common.alert('下载成功');
						},
						fail:function(){
							common.alert('下载失败');
						},
					});
				}
			},
			fail(error){
				console.log(error, file);
			}
		});
	},
	downloadVideo:function(file){
		common.alert('下载视频中...');
		uni.downloadFile({
			url: file,
			success: (res) => {
				if (res.statusCode === 200) {
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: function () {
							common.alert('图片已保存到相册');
						},
						fail:function(){
							common.alert('图片保存相册失败');
						},
					});
				}
			},
		});
	},
	preview:function(images, current=0){
		uni.previewImage({
			current:current,
            urls: images,
            longPressActions: {
                itemList: ['保存图片'],
                success: function(data) {
					if(data.tapIndex == 0){
						HttpRequest.downloadFileSavePhoto(images[data.index]);
					}
					console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
                },
                fail: function(err) {
                    console.log(err.errMsg);
                }
            }
        });
	},
	getRandomInt(min,max){
		return Math.floor(Math.random()*(max-min+1))+min;
	},
	getLocation(){
		uni.getLocation({
			success:function(res){
				common.setData('longitude', res.longitude);
				common.setData('latitude', res.latitude);
			},
			fail:function(res){
				console.log(res);
			}
		})
	},
	getQueryParams(paramsString) {
		return paramsString.split('&').reduce((params, param) => {
			param = decodeURIComponent(param);
			let [key, value] = param.split('=');
			params[key] = value;
			return params;
		}, {});
	},
	//首次打开小程序执行登录再执行其它接口，注意分享页面
	wxLogin(callback,error){
		console.log('登录wxlogin');
		wx.login({
			success: res=>{
				appData.auth.loginByWxOpenid({code:res.code}, function(resp){
					console.log('login',resp);
					common.setData('openid', resp.data.openid);
					common.setData('session_key', resp.data.session_key);
					common.setData('token', resp.data.token);
					common.setData('invite_code', resp.data.invite_code);
					if(resp.data?.token){
						callback();
					}else{
						if(error){error()}
					}
				});
			}
		});
	},
	timeDifference(startTime,endTime){
		let timeVal = Math.abs(endTime - startTime)
		let hours = Math.floor(parseInt(timeVal)/1000/3600)
		let minutes = Math.floor(parseInt(timeVal)/1000/60)
		let seconds = Math.floor(parseInt(timeVal)/1000)
		minutes = (minutes % 60) >9?(minutes % 60):'0'+(minutes % 60)
		seconds = (seconds % 60) >9?(seconds % 60):'0'+(seconds % 60)
		hours = hours >9 ?hours:'0'+hours
		return {
			h:hours,
			m:minutes,
			s:seconds
		}
	}
} 

export default common;